<?php
/**
 * 页面显示帮助类
 * 
 * @copyright  vincent
 * @license    Mediad License
*/
class Mediad2_Utility_SmartyHelper
{   
	
	/**
	 * @param string $url 网址或网络文件
	 * @return Array: boolean /head 网址/文件是否可读  具体response头信息
	 * @author vincent 20121213
	 */
	public function url_exists($url)
	{
		$head = @get_headers($url);
		$isUrl =is_array($head) ? true : false;
		return Array("isurl"=>$isUrl,"head"=>$head);
	}
	/**
	 * 日志记录 DEBUG用
	 * @param string $mes 内容
	 * @param string $filepath log保存路径
	 */
	public function log($mes,$filepath="d:\\log.txt"){			
		$fh = fopen($filepath, 'a') or die("can't open file");	
		fwrite($fh, "[".date("H:i:s")."]$mes \r \n");	
		fclose($fh);	
	}	
	/**
	 * 通过PATH将文件拷贝在缓存目录中[vincent][20120831]
	 * @param 缓存路径
	 * @return string|NULL
	 */
	public function getCachepath($path){
		if(is_file($path)){
			$array = explode("\\",$path);
			$fileName = $array[count($array)-1];
			copy($path, CACHE_LOCATION.$fileName);
			return CACHE_PATH.$fileName;
		}
		return null;
	}
		
	public function getDateCount($date1,$date2){
		$isSameYear = true;
		//天数
		$dayCount = 1 + (strtotime($date1)-strtotime($date2))/86400;
		
		$dayDetail1 = $this->getDateDetail($date1);
		$dayDetail2 = $this->getDateDetail($date2);
		
		if ($dayDetail1["y"]!=$dayDetail2["y"]){
			$isSameYear = false;
		}
		
		if($isSameYear){
			//查询日期1的天数
			$day1 = $this->getMonthCount($date1);
			//查询日期2的天数
			$day2 = $this->getMonthCount($date2);			
		}else{
			//年份大的日期顺序计算日期，年份小的日期倒序计算日期
			if($dayDetail1["y"]>$dayDetail2["y"]){
				//DAY1 大				
				$day1 = $this->getMonthCount($date1,"desc");				
				$day2 = $this->getMonthCount($date2);
			}else{
				//DAY2 大
				$day1 = $this->getMonthCount($date1);
				$day2 = $this->getMonthCount($date2,"desc");
			}			
		}
				
		if($dayCount<0){
			$dayCount = $dayCount*(-1);
		}	
	}
	
	public function getMonths($date,$orderby="asc"){
		$key = $this->getDateDetail($date);		
		$months = null;
		switch ($orderby){
			case "asc":				
				for($m = $key["m"];$m <12+1;$m++){
					$months[$m] =$m;
				}
				break;
			case "desc":
				for($m = 1;$m <$key["m"]+1;$m++){
					$months[$m] =$m;
				}				
				break;
		}
		return $months;		
	}
	
// 	public function setMonths($months)
// 	{
// 		$value = null;
// 		for ($m=1;$m<count($months);$m++){
// 			if($m==$months[$m]){
// 				//TODO:
// 				$days= date("Y-m-d",mktime(0,0,0,$value["m"],date("t",strtotime($date)),$value["y"]));
// 				for ($i=1;$i<$days+1;$i++){
// 						if(strlen($i)!=2){
// 							$dateString ='0'.$i;
// 						}else{
// 							$dateString =$i;
// 						}
	
// 						//构建日期
// 						$datex[] = $dateString;
// 						$number[$dateString] = "0";
// 						$number2[$dateString] = "0";
// 					}
// 			}
// 		}
// 	}
	
	/**
	 * @param 日期 $date
	 * @param 顺序/倒序 $status asc/desc
	 * @return 天数
	 */
	public function getMonthCount($date,$orderby='asc'){
		$value = $this->getDateDetail($date);
		$endday = null;
		$count = 1;
		switch ($orderby){
			case "desc":				
				$endday=$value["y"]."-".$value["m"]."-01";
				if($endday != $date){					
					$count = $count + (strtotime($date)-strtotime($endday))/86400;
				}				
				break;
			case "asc":
				$endday =date("Y-m-d",mktime(0,0,0,$value["m"],date("t",strtotime($date)),$value["y"]));
				if($endday != $date){					
					$count = $count + (strtotime($endday)-strtotime($date))/86400;
				}
				break;
		}
		return $count;
	}
	
	/**
	 * @param 日期值 $date
	 * @param 格式：默认年月日 $format
	 * @return array
	 */
	public function getDateDetail($date,$format='YMD'){
		//年月日
		$key = explode('-',$date);
		$value["y"] = $key[0];
		$value["m"] = $key[1];
		$value["d"] = $key[2];
		return $value;
	}
	
	/**
	 * @param string $type 1:返回当前月份总数 2:返回当前月份第一天和最后一天
	 * @param string $month 是否对月份赋值
	 * @return object
	 */
	public function getDateByMonth($type,$month=null,$year=null){
		if(empty($year)){
			$year = date("Y");
		}
		if(empty($month)){
			$month = date("m");
		}
		$days = date("t",strtotime($year."-".$month."-01"));
		
		switch ($type){
			case 1:				
				$result = $days;
				break;
			case 2:
				if(strlen($month)==1){
					$month="0".$month;
				}
				$result = array($year."-".$month."-01",$year."-".$month."-".$days);
				break;
		}
		return $result;
	}
	/**
	 * 构建登录验证数字PNG
	 * @return Ambigous <NULL, string>
	 */
	public static function getValidatePicture()
	{
		//文件头...
		// header("Content-type: image/png");
		
		//创建真彩色白纸
		$im = @imagecreatetruecolor(50, 20) or die("建立图像失败");
		//获取背景颜色
		$background_color = imagecolorallocate($im, 255, 255, 255);
		//填充背景颜色(这个东西类似油桶)
		imagefill($im,0,0,$background_color);
		//获取边框颜色
		$border_color = imagecolorallocate($im,200,200,200);
		//画矩形，边框颜色200,200,200
		imagerectangle($im,0,0,49,19,$border_color);
		
		//逐行炫耀背景，全屏用1或0
		for($i=2;$i<18;$i++){
			//获取随机淡色
			$line_color = imagecolorallocate($im,rand(200,255),rand(200,255),rand(200,255));
			//画线
			// imageline($im,2,$i,47,$i,$line_color);
		}
		
		//设置字体大小
		$font_size=12;
		
		//设置印上去的文字
		$Str[0] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		$Str[1] = "abcdefghijklmnopqrstuvwxyz";
		$Str[2] = "01234567891234567890123456";
		
		//获取第1个随机文字
		$imstr[0]["s"] = $Str[rand(0,2)][rand(0,25)];
		$imstr[0]["x"] = rand(2,5);
		$imstr[0]["y"] = rand(1,4);
		
		//获取第2个随机文字
		$imstr[1]["s"] = $Str[rand(0,2)][rand(0,25)];
		$imstr[1]["x"] = $imstr[0]["x"]+$font_size-1+rand(0,1);
		$imstr[1]["y"] = rand(1,3);
		
		//获取第3个随机文字
		$imstr[2]["s"] = $Str[rand(0,2)][rand(0,25)];
		$imstr[2]["x"] = $imstr[1]["x"]+$font_size-1+rand(0,1);
		$imstr[2]["y"] = rand(1,4);
		
		//获取第4个随机文字
		$imstr[3]["s"] = $Str[rand(0,2)][rand(0,25)];
		$imstr[3]["x"] = $imstr[2]["x"]+$font_size-1+rand(0,1);
		$imstr[3]["y"] = rand(1,3);

		//session保存值
		$sessionValue = null;
		for ($i=0;$i<4;$i++){
			$sessionValue = $sessionValue.$imstr[$i]["s"];
		}
		
// 		if(!isset($_SESSION['vk'])){
// 			session_start();
// 			$_SESSION['vk'] = $sessionValue;
// 		}
		
		//写入随机字串
		for($i=0;$i<4;$i++){
			//获取随机较深颜色
			$text_color = imagecolorallocate($im,rand(50,180),rand(50,180),rand(50,180));
			//画文字
			imagechar($im,$font_size,$imstr[$i]["x"],$imstr[$i]["y"],$imstr[$i]["s"],$text_color);
		}
		
		//显示图片
		$num = rand(0, 9);
		$pic = "verify".$num.".png";	
		$url = VKIMG_PATH.$pic;		
		imagepng($im,$url);

		$returnValue['pic'] = $pic;
		$returnValue["key"] = $sessionValue;
		
		//销毁图片
		imagedestroy($im);
		return $returnValue;
	}
	
	/**
	 * @param int $initYear 初始年份,如2011
	 * @return array <name, value> 返回select的值和显示内容 
	 */
	public static function getSearchDate($initYear=null){
		if(empty($initYear)){
			$initYear 	= 2011;
		}
						
		$initMonth 	= 12;
		$startYear 	= getdate();
		$yearCount 	= $startYear['year'] - $initYear;
		
		$name 		= null;
		$value      = null;
		
		$dd = date("Y-m-d H:i:s");
		for($i=0;$i<$yearCount;$i++){
			for($m=1;$m<$initMonth+1;$m++){
				$year = $initYear+$i+1;
				$name[]= $m." 月 ".$year;
				if(strlen($m)==1){
					$value[] = $year."-0".$m;
				}else{
					$value[] = $year."-".$m;
				}
				 
			}
		}
		return array($name,$value);		
	}
	
	/**
	 * 页面设置
	 * @param string $view 视图实例
	 * @param string $title 标题
	 * @param string $pagename  页面地址
	 * @param array $values  超链接
	 */
	public static function setPageView($view,$title, $pagename, $values) {		
		if (! empty ( $title ) && ! empty ( $pagename )) {			
			$view->assign ( 'title', $view->translate ( $title ) ); //标题			
			if (! empty ( $values )) {
				$view->assign ( "linked", $values );
			}
			$view->assign ( 'default', $pagename );
			$view->render ( $pagename . '.tpl.html' );
		}
	}
	
    /**
     * @param View $view 视图实例
     * @param String $templates 模板目录
     */
    public static function setSmarty($view,$templates)
    {
    	if(empty($view))return;
    	if(empty($templates))return;
    	if (! defined ( 'WEB_PATH' )) {
    		echo "网站部署路径获取失败";
    		return;
    	}
    	
    	$view->setScriptPath ( $templates ); //设置模板目录
    	
    	//预置Head Foot页面参数
//     	$view->assign ( "headmenu", array ("首页", "手机用户", "广告主", "广告代理商", "平台合作商" ) ); //head导航
//     	$view->assign ( "headmenuen", array ("index", "mobile", "ad", "agent", "partner", "news" ) ); //head导航
    	$view->assign ( "headmenu", array ("首页", "手机用户" ) ); //head导航
    	$view->assign ( "headmenuen", array ("index", "mobile") ); //head导航
    	
    	
    	$view->assign ( "headmenuLink", array (WEB_PATH, WEB_PATH . "index/mobile", WEB_PATH . "index/adowner", WEB_PATH . "index/agent", WEB_PATH . "index/partner", WEB_PATH . "index/news" ) ); //导航link    	
    	$view->assign ( "footmenu", array ("关于金矿", "服务条款", "隐私声明", "联系我们","网站地图" ) ); //foot导航
    	$view->assign ( "footmenuen", array ("about", "statement", "agreement", "contact","sitemap" ) ); //foot导航
    	$view->assign ( "footmenuLink", array (WEB_PATH . "index/about", WEB_PATH . "index/statement", WEB_PATH . "index/agreement", WEB_PATH . "index/contact",WEB_PATH . "index/sitemap" ) ); //导航link    	
    	$view->assign ( "keyword", array ("name" => "帐号", "pwd" => "密码", "login" => "登录", "forget" => "忘记密码", "register" => "注册" ) );
    	$view->assign ( "link", array ("login" => WEB_PATH . "index/login", "forget" => WEB_PATH . "index/forget", "register" => WEB_PATH . "index/register" ) );
    	
    	Zend_Registry::set ( 'view', $view );
    }
    
    //旧方法
    public static function setBackPageView($view,$title, $pagename, $pageStatus) {
    	if (! empty ( $title ) && ! empty ( $pagename )&&!empty($pageStatus)) {    		
    		$smarty = $view;
    		$smarty->assign ( 'title', $view->translate ( $title ) ); //标题    	
    	
    		$url = WEB_PATH . $pageStatus."/";
    	
    		switch ($pageStatus) {
    			case "mobile" : //手机用户
    				//menu
    				$smarty->assign ( "pagestatus", $pageStatus );
    				$smarty->assign ( "menucn", array ("用户兑换", "用户信息" ) );
    				$smarty->assign ( "menuen", array ("pay", "userinfo" ) );
    				$smarty->assign ( "menulink", array ($url . "pay", $url . "userinfo" ) );
    	
    				//左侧
    				$smarty->assign ( "menutitle", array ("导航区", "用户兑现", "用户信息" ) );
    	
    				$smarty->assign ( "paymenu", array ("我要兑现", "兑现记录表", "点击记录", "用户访问记录", "用户行为", "用户行为记录" ) );
    				$smarty->assign ( "userinfomenu", array ("用户详细信息", "修改密码" ) );
    	
    				$smarty->assign ( "paymenuname", array ("pay", "payrec", "clkrec", "reqrec", "behavior", "behrec" ) );
    				$smarty->assign ( "userinfomenuname", array ("userinfo", "chpwd" ) );
    	
    				$smarty->assign ( "paymenulink", array ($url . "pay", $url . "payrec", $url . "clkrec", $url . "reqrec", $url . "behavior", $url . "behrec" ) );
    				$smarty->assign ( "userinfomenulink", array ($url . "userinfo", $url . "chpwd" ) );
    				break;
    			case "admin" : //系统用户
    				//menu
    				$smarty->assign ( "pagestatus", $pageStatus );
    	
    				//左侧
    				$smarty->assign ( "menutitle", array ("手机用户管理", "资源管理",  "系统用户管理" ) );    	
    				
    				$smarty->assign ( "mobmenu", array ("手机用户列表", "用户兑现申请", "用户兑现审批","用户兑现记录","用户帐号表" ) );    				    				
    				$smarty->assign ( "minemenu", array ("矿产资源列表", "滚动新闻列表"  ) );    				
    				$smarty->assign ( "adminmenu", array ("系统用户列表", "角色管理","权限管理","模板管理","序列管理","字典列表", "字典类型" ) );    				
    				
    				$smarty->assign ( "mobmenuname", array ("personinfo", "exchangeapp", "exchangeaudit","accountally","accountinfo" ) );    				    				
    				$smarty->assign ( "minemenuname", array ("goldminetask", "rollmessage" ) );    				
    				$smarty->assign ( "adminmenuname", array ("member", "roleman","permission","module","sequence","dictlist", "dicttype" ) );    	
    				
    				$smarty->assign ( "mobmenulink", array ($url . "personinfo", $url ."exchangeapp", $url ."exchangeaudit",$url ."accountally",$url ."accountinfo" ) );    				    				
    				$smarty->assign ( "minemenulink", array ($url ."goldminetask",$url ."rollmessage") );    				
    				$smarty->assign ( "adminmenulink", array ($url ."member", $url ."roleman",$url ."permission",$url ."module",$url ."sequence",$url . "dictlist", $url . "dicttype" ) );
    				
    				break;
    		}
    		$registry = Zend_Registry::getInstance ();
    		$identity =  $registry->auth->getIdentity();
    		$account=$identity->UserInfo->UserAccount;
    		$smarty->assign ( "MediadUser", array ($account) );    		
    		$smarty->assign ( 'default', $pagename );
    		$smarty->render ( $pagename . '.tpl.html' );
    	}
    }
}

